// UserProfileDataStore.kt
package com.example.nutritionmanager.data

import android.content.Context
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.preferencesDataStore
import com.example.nutritionmanager.bodys.responseBodys.UserProfileResponse
import com.google.gson.Gson
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import javax.inject.Inject
import javax.inject.Singleton

@Singleton
class UserProfileDataStore @Inject constructor(
    @ApplicationContext private val context: Context
) {

    companion object {
        private val Context.userProfileDataStore by preferencesDataStore(name = "user_profile")
        private val USER_PROFILE_KEY = stringPreferencesKey("user_profile")
        private val gson = Gson()
    }

    // 保存用户资料
    suspend fun saveUserProfile(userProfile: UserProfileResponse) {
        context.userProfileDataStore.edit { preferences ->
            preferences[USER_PROFILE_KEY] = gson.toJson(userProfile)
        }
    }

    // 读取用户资料
    val getUserProfile: Flow<UserProfileResponse?> = context.userProfileDataStore.data
        .map { preferences ->
            preferences[USER_PROFILE_KEY]?.let { json ->
                gson.fromJson(json, UserProfileResponse::class.java)
            }
        }

    // 清除用户资料（例如登出时）
    suspend fun clearUserProfile() {
        context.userProfileDataStore.edit { preferences ->
            preferences.remove(USER_PROFILE_KEY)
        }
    }

    suspend fun getCurrentUserProfile(): UserProfileResponse? {
        return getUserProfile.first()
    }

    // 添加获取最大热量的Flow
    val maxCalorie: Flow<Int> = getUserProfile.map {
        it?.targetCalories ?: 2000
    }
}
